﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Hotnet.Entity;
using Hotnet.Biz.NSBizPicture;
using System.IO;
using Hotnet.Biz.NSBizCommon;
using Hotnet.Web.MVCExtension;
using Hotnet.Web.Utility;
using Component.Utilities;
using Hotnet.Biz.Properties;
using ZoomImageDemo;

namespace Hotnet.Web.Controllers.Admin
{
	public class AdminPictureController : AdminBaseController
	{
		//
		// GET: /AdminPicture/
		private BizPicture _BizPicture;
		private BizPicture BizPicture
		{
			get
			{
				if (_BizPicture == null)
					_BizPicture = new BizPicture();
				return _BizPicture;
			}
		}
		private BizPictureGroup _BizPictureGroup;
		private BizPictureGroup BizPictureGroup
		{
			get
			{
				if (_BizPictureGroup == null)
					_BizPictureGroup = new BizPictureGroup();
				return _BizPictureGroup;
			}
		}
		private BizPictureCategory _BizPictureCategory;
		private BizPictureCategory BizPictureCategory
		{
			get
			{
				if (_BizPictureCategory == null)
					_BizPictureCategory = new BizPictureCategory();
				return _BizPictureCategory;
			}
		}
		private BizSourceFrom bizSourceFrom;
		private BizSourceFrom BizSourceFrom
		{
			get
			{
				if (bizSourceFrom == null)
				{
					bizSourceFrom = new BizSourceFrom();
				}
				return bizSourceFrom;
			}
		}

		public ActionResult Index()
		{
			return View();
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Delete(int id)
		{
			Picture pic = BizPicture.Get(id);
			BizPicture.Delete(id);
			return RedirectToAction("Index", "AdminPictureGroup", new { id = pic.GroupID });
		}

		public ActionResult UploadImage(int categoryId, int groupId)
		{
			PictureCategory category = BizPictureCategory.Get(categoryId);
			ViewData["Category"] = category;

			PictureGroup group = BizPictureGroup.Get(groupId);
			ViewData["Group"] = group;

			return View();
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult UploadImage(int groupId)
		{
			if (Request.Files != null && Request.Files.Count > 0)
			{
				Picture picture = null;
				for (int i = 0; i < Request.Files.Count; i++)
				{
					HttpPostedFileBase imageFile = Request.Files[i];

					if (imageFile.ContentLength <= 0)
						continue;
					picture = new Picture();
					picture.GroupID = groupId;
					picture.OrderInGroup = 0;
					picture.AddTime = DateTime.Now;
					BizPicture.AddPicture(picture);

					try
					{
						string imageName = null;
						string dir = StringUtility.GetSavePath(picture.PictureID, out imageName);

						picture.LocalPath = dir + imageName + "_o" + Path.GetExtension(imageFile.FileName);
						picture.ThumbnailPath = dir + imageName + "_t" + Path.GetExtension(imageFile.FileName);
						BizPicture.Update(
							picture.PictureID,
							pic => new Picture
							{
								LocalPath = picture.LocalPath,
								ThumbnailPath = picture.ThumbnailPath
							}
						);
						string folder = Settings.Default.UploadFolder.Substring(1);
						string str = string.Format("{0}{1}{2}", AppDomain.CurrentDomain.BaseDirectory, folder, dir);
						Directory.CreateDirectory(str);
						imageFile.SaveAs(string.Format("{0}{1}{2}", AppDomain.CurrentDomain.BaseDirectory, folder, picture.LocalPath));

						ImagePlus imagePlus = new ImagePlus(imageFile.InputStream);
						imagePlus.MakeThumbnail(160, 120,2);
						imagePlus.SaveAs(string.Format("{0}{1}{2}", AppDomain.CurrentDomain.BaseDirectory, folder, picture.ThumbnailPath));
					}
					catch
					{
						BizPicture.Delete(picture.PictureID);
						throw;
					}
				}
			}
			return Content("1");
		}

		public ActionResult PictureCrop(int pictureId)
		{
			Picture image = BizPicture.Get(pictureId);
			ViewData["PictureSrc"] = Biz.Properties.Settings.Default.UploadFolder+image.LocalPath;
			ViewData["PictureGroupID"] = image.GroupID;
			return View();
		}
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult PictureCrop(int pictureId,string txt_width, string txt_height, string txt_top, string txt_left, string txt_DropWidth, string txt_DropHeight)
		{
			int imageWidth = Int32.Parse(txt_width);
			int imageHeight = Int32.Parse(txt_height);
			int cutTop = Int32.Parse(txt_top);
			int cutLeft = Int32.Parse(txt_left);
			int dropWidth = Int32.Parse(txt_DropWidth);
			int dropHeight = Int32.Parse(txt_DropHeight);
			Picture image= BizPicture.Get(pictureId);

			string filename = CutPhotoHelp.SaveCutPic(Server.MapPath(Biz.Properties.Settings.Default.UploadFolder + image.LocalPath), Server.MapPath(Biz.Properties.Settings.Default.UploadFolder + image.ThumbnailPath), 0, 0, dropWidth,
									dropHeight, cutLeft, cutTop, imageWidth, imageHeight);
			//this.imgphoto.ImageUrl = savepath + filename;
			ViewData["PictureSrc"] = Biz.Properties.Settings.Default.UploadFolder + image.LocalPath;
			ViewData["PictureCrop"] = Biz.Properties.Settings.Default.UploadFolder + image.ThumbnailPath;
			ViewData["PictureGroupID"] = image.GroupID;
			return View();
		}

		public ActionResult EditBatch(int categoryId, int groupId)
		{

			var pictures = BizPicture.ListByGroupID(groupId);

			PictureCategory category = BizPictureCategory.Get(categoryId);
			ViewData["Category"] = category;

			PictureGroup group = BizPictureGroup.Get(groupId);
			ViewData["Group"] = group;

			SourceFrom[] sourceFrom = BizSourceFrom.List();
			SelectList sourceFromList = new SelectList(sourceFrom, "SourceFromID", "Name", null);
			ViewData["SourceFromList"] = sourceFromList;

			return View(pictures);
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult EditBatch()
		{

			var pictures = BizPicture.ListByGroupID(Convert.ToInt32(Request["groupId"]));

			var pictureIds = Request["pictureIds"].Split(',');

			foreach (var pid in pictureIds)
			{
				int id = Convert.ToInt32(pid);
				int orderNo = 0;
				string s_orderNo = (Request["order" + pid] ?? "").Trim();
				if (!string.IsNullOrEmpty(s_orderNo))
					orderNo = Convert.ToInt32(s_orderNo);

				BizPicture.Update(
					pic => pic.PictureID == id,
					pic => new Picture { Description = Request["desc" + pid].Trim(), OrderInGroup = orderNo }
				);
			}

			return RedirectToAction("Index", "AdminPictureGroup", new { id = Request["groupId"] });
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Edit(Picture picture)
		{
			BizPicture.Update(pic => pic.PictureID == picture.PictureID,
				pic => new Picture { Description = picture.Description, OrderInGroup= picture.OrderInGroup }
			);
			return RedirectToAction("Index", "AdminPictureGroup", new { id = picture.GroupID });
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public void SetGroupCoverImage(int pictureId, int groupId)
		{
			BizPictureGroup.Update(
				group => group.GroupID == groupId,
				group => new PictureGroup { CoverImageID = pictureId }
			);
		}

		public ActionResult Get(int id)
		{
			var picture = BizPicture.Get(id);
			return Json(picture);
		}

	}
}
